﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebSoftSeo.Models;
using WebSoftSeo.Utility;

namespace WebSoftSeo.Areas.Admin.Controllers
{
    public class NewsController : Controller
    {
        private WebSoftSeoEntities db = new WebSoftSeoEntities();

        //
        // GET: /Admin/News/

        public ActionResult Index()
        {
            News Banner = db.News.Where(m => m.IsBanner == true).FirstOrDefault();
            if (Banner != null)
            {
                ViewBag.Banner = Banner;
            }
            return View(db.News.Where(m=>m.IsBanner == false || m.IsBanner == null).ToList());
        } 

        //
        // GET: /Admin/News/Details/5

        public ActionResult Details(int id = 0)
        {
            News news = db.News.Find(id);
            if (news == null)
            {
                return HttpNotFound();
            }
            return View(news);
        }


        private ImageCodecInfo GetEncoderInfo(String mimeType)
        {
            int j;
            ImageCodecInfo[] encoders;
            encoders = ImageCodecInfo.GetImageEncoders();
            for (j = 0; j < encoders.Length; ++j)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            return null;
        }
        //
        // GET: /Admin/OurClient/Create
        public void Resize(string ImageSavePath, string fileName, int MaxWidthSideSize, int MaxHeightSidesize, Stream Buffer)
        {
            int intNewWidth;
            int intNewHeight;
            System.Drawing.Image imgInput = System.Drawing.Image.FromStream(Buffer);
            ImageCodecInfo myImageCodecInfo;
            myImageCodecInfo = GetEncoderInfo("image/jpeg");
            //
            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
            EncoderParameters myEncoderParameters = new EncoderParameters(1);
            EncoderParameter myEncoderParameter;
            //Giá trị width và height nguyên thủy của ảnh;
            int intOldWidth = imgInput.Width;
            int intOldHeight = imgInput.Height;

            //Kiểm tra xem ảnh ngang hay dọc;
            int intMaxSideW;
            int intMaxSideH;
            /*if (intOldWidth >= intOldHeight)
            {
            intMaxSide = intOldWidth;
            }
            else
            {
            intMaxSide = intOldHeight;
            }*/
            //Để xác định xử lý ảnh theo width hay height thì bạn bỏ note phần trên;
            //Ở đây mình chỉ sử dụng theo width nên gán luôn intMaxSide= intOldWidth; ^^;
            intMaxSideW = intOldWidth;
            intMaxSideH = intOldHeight;
            if (intMaxSideW > MaxWidthSideSize | intMaxSideH > MaxHeightSidesize)
            {
                //Gán width và height mới.
                double dblCoefW = MaxWidthSideSize / (double)intMaxSideW;
                intNewWidth = Convert.ToInt32(dblCoefW * intOldWidth);
                double dblCoefH = MaxHeightSidesize / (double)intMaxSideH;
                intNewHeight = Convert.ToInt32(dblCoefH * intOldHeight);
            }
            else
            {
                //Nếu kích thước width/height (intMaxSide) cũ ảnh nhỏ hơn MaxWidthSideSize thì giữ nguyên //kích thước cũ;
                intNewWidth = intOldWidth;
                intNewHeight = intOldHeight;
            }


            //Tạo một ảnh bitmap mới;
            Bitmap bmpResized = new Bitmap(imgInput, intNewWidth, intNewHeight);
            //Phần EncoderParameter cho phép bạn chỉnh chất lượng hình ảnh ở đây mình để chất lượng tốt //nhất là 100L;
            myEncoderParameter = new EncoderParameter(myEncoder, 100L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            //Lưu ảnh;
            bmpResized.Save(ImageSavePath + fileName, myImageCodecInfo, myEncoderParameters);

            //Giải phóng tài nguyên;
            //Buffer.Close();
            imgInput.Dispose();
            bmpResized.Dispose();
        }
        //
        // GET: /Admin/News/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Admin/News/Create

        [HttpPost, ValidateInput(false)]
        public ActionResult Create(News news)
        {
            if (ModelState.IsValid)
            {
                String NamePro = null;

                if (Request.Files["img1"] != null)
                {
                    HttpPostedFileBase file0 = Request.Files["img1"];
                    string fullname = Request.Files["img1"].FileName;
                    if (fullname != "")
                    {
                        NamePro = fullname.Substring(1 + fullname.LastIndexOf("\\"));
                        string rename = HelperSEO.ToSeoImage(news.Title + DateTime.Now.Ticks + NamePro.Substring(NamePro.LastIndexOf(".")));
                        Resize(Server.MapPath("~/Images/News/"), rename, 737, 334, file0.InputStream);
                        //Resize(Server.MapPath("~/Images/OurClient/Img80.80/"), rename, , 80, file0.InputStream);
                        news.ImagePath = rename;
                    }
                }
                news.CreatedDate = DateTime.Now;
                db.News.Add(news);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(news);
        }

        //
        // GET: /Admin/News/Edit/5

        public ActionResult Edit(int id = 0)
        {
            News news = db.News.Find(id);
            if (news == null)
            {
                return HttpNotFound();
            }
            return View(news);
        }
        public ActionResult EditBanner(int id = 0)
        {
            News news = db.News.Find(id);
            if (news == null)
            {
                return HttpNotFound();
            }
            return View(news);
        }
        //
        // POST: /Admin/News/Edit/5

        [HttpPost, ValidateInput(false)]
        public ActionResult Edit(News news)
        {
            if (ModelState.IsValid)
            {
                String NamePro = null;

                if (Request.Files["img1"] != null)
                {
                    HttpPostedFileBase file0 = Request.Files["img1"];
                    string fullname = Request.Files["img1"].FileName;
                    if (fullname != "")
                    {
                        NamePro = fullname.Substring(1 + fullname.LastIndexOf("\\"));
                        string rename = HelperSEO.ToSeoImage(news.Title + DateTime.Now.Ticks + NamePro.Substring(NamePro.LastIndexOf(".")));
                        Resize(Server.MapPath("~/Images/News/"), rename, 737, 334, file0.InputStream);
                        //Resize(Server.MapPath("~/Images/OurClient/Img80.80/"), rename, , 80, file0.InputStream);
                        news.ImagePath = rename;
                    }
                }
                news.CreatedDate = DateTime.Now;
                db.Entry(news).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(news);
        }

        //
        // GET: /Admin/News/Delete/5

        public ActionResult Delete(int id = 0)
        {
            News news = db.News.Find(id);
            if (news == null)
            {
                return HttpNotFound();
            }
            return View(news);
        }

        //
        // POST: /Admin/News/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            News news = db.News.Find(id);
            db.News.Remove(news);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}